package com.zt.bus.assistant.service;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.bus.assistant.inter.NoticeMapper;
import com.zt.bus.assistant.model.Notice;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.StringUtil;

import java.util.Date;

@Service
public class NoticeService extends BaseService {

    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 查询
     *
     * @param reqBean
     * @return
     */
    public JSONObject findNotice(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("select n.*  from DZ_NOTICE n where 1=1", new Object[0]);
        sqlBuilder.addWhereLike2("n.TITLE", reqBean.getInfo("title"));
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 新增
     *
     * @param reqBean
     */
    public void addNotice(ReqBean reqBean) {
        Notice notice = getNotice(reqBean);
        notice.setId(intIncrementId("DZ_NOTICE", "ID"));// 手动设置Id
        notice.setMakeTime(notice.getModifyTime());
        noticeMapper.insert(notice);
    }

    /**
     * 修改
     *
     * @param reqBean
     */
    public void updateNotice(ReqBean reqBean) {
        String id = reqBean.getInfo("id");
        if (StringUtil.isEmpty(id)) {
            throw new BusinessException("获取主键失败");
        }
        Notice notice = getNotice(reqBean);
        noticeMapper.updateByPrimaryKeySelective(notice);
    }

    /**
     * 删除
     *
     * @param reqBean
     */
    public void removeNotice(ReqBean reqBean) {
        String id = reqBean.getInfo("id");
        if (StringUtil.isEmpty(id)) {
            throw new BusinessException("获取主键失败");
        }
        noticeMapper.deleteByPrimaryKey(id);
    }

    /**
     * 从表单获取对象
     *
     * @param reqBean
     * @return
     */
    private Notice getNotice(ReqBean reqBean) {
        Notice notice = new Notice();

        notice.setId(reqBean.getInfo("id"));
        notice.setTitle(reqBean.getInfo("title"));
        notice.setContent(reqBean.getInfo("content"));
        notice.setAndroidContent(reqBean.getInfo("androidContent"));
        notice.setNoticeOrder(reqBean.getInfoInt("order"));
        notice.setType(reqBean.getInfoInt("type"));
        notice.setOperator(reqBean.getUserId());
        notice.setMakeTime(DateUtil.parseDateTime(reqBean.getInfo("makeTime")));
        notice.setModifyTime(new Date());
        notice.setRemark(reqBean.getInfo("remark"));

        return notice;
    }

    public JSONArray query4Mobile(ReqBean reqBean) {
        String sql = "select *  from DZ_NOTICE ORDER BY NOTICE_ORDER ASC";
        return query(sql);
    }
}